89. 格雷编码
为保证权益,题目请参考 89. 格雷编码(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
class Solution
{
public:
vector<int> grayCode(int n)
{
vector<int> ans(pow(2, n), 0);
ans[0] = 0;
ans[1] = 1;
for (int i = 1; i < n; i++)
{
for (int j = pow(2, i); j < pow(2, i + 1); j++)
{
ans[j] = (1 << i) + ans[pow(2, i) - (j - pow(2, i)) - 1];
}
}
return ans;
}
};
int main()
{
Solution so;
for (auto x : so.grayCode(4))
{
cout << x << endl;
}
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Python
python
# 89. 格雷编码
# https://leetcode-cn.com/problems/gray-code/
from typing import List
class Solution:
def grayCode(self, n: int) -> List[int]:
ans = [0]
for i in range(n):
t = len(ans)
for j in range(t - 1, -1, -1):
ans.append(ans[j] ^ (1 << i))
return ans
if __name__ == "__main__":
solution = Solution()
print(solution.grayCode(2))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19